function CropAvatar(options) {
    var defaults = {
        container: '#crop-avatar',
        workspaces: '__ROOT__',
        formUrl: '',
        submitDone:function (data) {
            var $avatarView = $('.avatar-view');
            if (data.state == 1) {
                var imgUrl = data.picpath;
                var imgUrlTH = data.data;

                var html = ' <div class="goods-img-item">';
                html += '<img style="max-height: 400px" src="' + options.workspaces + imgUrl + '" alt="">';
                html += '<span class="glyphicon close-goods-img glyphicon-remove-circle"></span>';
                html += '</div>';

                $avatarView.before(html);
                $avatarView.siblings("input[name='picpath']").val(imgUrl);
                $avatarView.siblings("input[name='thumbpicpath']").val(imgUrlTH);
                $avatarView.hide();

                $avatarView.parents(".form-group").removeClass("has-error").addClass("has-success");
                $avatarView.parents(".form-group").find(".help-block").hide();

                $(options.container).find('#avatar-modal').modal('hide');
            } else {
                alert('Failed to response');
            }
        },
        delete:function (e) {
            var _this = e.target;
            var flag = _this.className.indexOf('close-goods-img');
            var $avatarView = $('.avatar-view');
            if (flag >= 0) {
                var $elem = $(_this);
                if (confirm("确认移除？")) {
                    $avatarView.show();
                    $elem.parent(".goods-img-item").remove();
                    $avatarView.next("input[name='thumbpicpath']").val("");
                    $avatarView.next("input[name='picpath']").val("");
                    $('.add-goods-img').attr('src',options.workspaces+'/Public/Boss/images/default.png')
                }
            }
        }
    };
    // 不管有没有传入参数，先合并再说；
    this.params = $.extend({}, defaults, options || {});

    this.$container = $(this.params.container);

    this.workspaces = this.params.workspaces;
    this.$goodsList = $(".goods-img-list");
    this.$closeImg = $(".close-goods-img");

    this.$avatarView = $('.avatar-view');
    this.$avatar = this.$avatarView;
    this.$avatarModal = this.$container.find('#avatar-modal');
    this.$loading = this.$container.find('.loading');

    this.$avatarForm = this.$avatarModal.find('.avatar-form');
    this.$avatarUpload = this.$avatarForm.find('.avatar-upload');
    this.$avatarSrc = this.$avatarForm.find('.avatar-src');
    this.$avatarData = this.$avatarForm.find('.avatar-data');
    this.$avatarInput = this.$avatarForm.find('.avatar-input');
    this.$avatarFigure = this.$avatarForm.find('.avatar-figure');
    this.$avatarSave = this.$avatarForm.find('.avatar-save');
    this.$avatarBtns = this.$avatarForm.find('.avatar-btns');

    this.$avatarWrapper = this.$avatarModal.find('.avatar-wrapper');
    this.$avatarPreview = this.$avatarModal.find('.avatar-preview');

    this.init();
}

CropAvatar.prototype = {
    constructor: CropAvatar,

    support: {
        fileList: !!$('<input type="file">').prop('files'),
        blobURLs: !!window.URL && URL.createObjectURL,
        formData: !!window.FormData
    },

    init: function () {
        this.support.datauri = this.support.fileList && this.support.blobURLs;
        this.aspectRatio = 1;

        this.$avatarFigure.val(1);

        if (!this.support.formData) {
            this.initIframe();
        }

        this.initTooltip();
        this.initModal();
        this.addListener();
    },

    addListener: function () {
        this.$avatarView.on('click', $.proxy(this.click, this));
        this.$avatarInput.on('change', $.proxy(this.change, this));
        this.$avatarForm.on('submit', $.proxy(this.submit, this));
        this.$avatarBtns.on('click', $.proxy(this.rotate, this));

        this.$goodsList.on("click", this.$closeImg, $.proxy(this.delete, this));
    },

    initTooltip: function () {
        this.$avatarView.tooltip({
            placement: 'bottom'
        });
    },

    initModal: function () {
        this.$avatarModal.modal({
            show: false
        });
    },

    initPreview: function () {
        // var url = this.$avatar.attr('src');
        //
        // this.$avatarPreview.empty().html('<img src="' + url + '">');
    },

    initIframe: function () {
        var target = 'upload-iframe-' + (new Date()).getTime(),
            $iframe = $('<iframe>').attr({
                name: target,
                src: ''
            }),
            _this = this;

        // Ready ifrmae
        $iframe.one('load', function () {

            // respond response
            $iframe.on('load', function () {
                var data;

                try {
                    data = $(this).contents().find('body').text();
                } catch (e) {
                    console.log(e.message);
                }

                if (data) {
                    try {
                        data = $.parseJSON(data);
                    } catch (e) {
                        console.log(e.message);
                    }

                    _this.submitDone(data);
                } else {
                    _this.submitFail('Image upload failed!');
                }

                _this.submitEnd();

            });
        });

        this.$iframe = $iframe;
        this.$avatarForm.attr('target', target).after($iframe.hide());
    },

    click: function () {
        this.$avatarModal.modal('show');
        this.initPreview();
    },
    delete: function (e) {
        this.params.delete(e);
    },
    change: function () {
        var files,
            file;

        if (this.support.datauri) {
            files = this.$avatarInput.prop('files');

            if (files.length > 0) {
                file = files[0];

                if (this.isImageFile(file)) {
                    if (this.url) {
                        URL.revokeObjectURL(this.url); // Revoke the old one
                    }

                    this.url = URL.createObjectURL(file);
                    this.startCropper();
                }
            }
        } else {
            file = this.$avatarInput.val();

            if (this.isImageFile(file)) {
                this.syncUpload();
            }
        }
    },

    submit: function () {
        if (!this.$avatarSrc.val() && !this.$avatarInput.val()) {
            return false;
        }

        if (this.support.formData) {
            this.ajaxUpload();
            return false;
        }
    },

    rotate: function (e) {
        var data;

        if (this.active) {
            data = $(e.target).data();
            if (data.method) {
                var options = {
                    aspectRatio: data.option
                };
                this.$img.cropper('setAspectRatio', data.option);
            }
        }
    },

    isImageFile: function (file) {
        if (file.type) {
            return /^image\/\w+$/.test(file.type);
        } else {
            return /\.(jpg|jpeg|png|gif)$/.test(file);
        }
    },

    startCropper: function () {
        var _this = this;

        if (this.active) {
            this.$img.cropper('replace', this.url);
        } else {
            this.$img = $('<img src="' + this.url + '">');
            this.$avatarWrapper.empty().html(this.$img);
            this.$img.cropper({
                preview: this.$avatarPreview.selector,
                crop: function (data) {
                    var json = [
                        '{"x":' + data.x,
                        '"y":' + data.y,
                        '"height":' + data.height,
                        '"width":' + data.width,
                        '"rotate":' + data.rotate + '}'
                    ].join();

                    _this.$avatarData.val(json);
                }
            });

            this.active = true;
        }
    },

    stopCropper: function () {
        if (this.active) {
            this.$img.cropper('destroy');
            this.$img.remove();
            this.active = false;
        }
    },

    ajaxUpload: function () {
        var url = this.params.formUrl,
            data = new FormData(this.$avatarForm[0]),
            _this = this;

        $.ajax(url, {
            type: 'post',
            data: data,
            dataType: 'json',
            processData: false,
            contentType: false,

            beforeSend: function () {
                _this.submitStart();
            },

            success: function (data) {
                _this.submitDone(data);
            },

            error: function (XMLHttpRequest, textStatus, errorThrown) {
                _this.submitFail(textStatus || errorThrown);
            },

            complete: function () {
                _this.submitEnd();
            }
        });
    },

    syncUpload: function () {
        this.$avatarSave.click();
    },

    submitStart: function () {
        this.$loading.fadeIn();
    },

    submitDone: function (data) {
        this.params.submitDone(data);
        this.$avatarView.parents(".form-group").removeClass("has-error").addClass("has-success");
        this.$avatarView.parents(".form-group").find(".help-block").hide();
        this.$avatarModal.modal('hide');
    },

    submitFail: function (msg) {
        this.alert(msg);
    },

    submitEnd: function () {
        this.$loading.fadeOut();
    },

    cropDone: function () {
        this.$avatarForm.get(0).reset();
        this.$avatar.attr('src', this.url);
        this.stopCropper();
        this.$avatarModal.modal('hide');
    },
    isUndefined: function (n) {
        return typeof n === 'undefined';
    },
    setAspectRatio: function (aspectRatio) {
        var options = this.options;

        if (!this.isUndefined(aspectRatio)) {
            options.aspectRatio = parseFloat(aspectRatio) || NaN; // 0 -> NaN

            if (this.built) {
                this.initCropBox();

                if (this.cropped) {
                    this.renderCropBox();
                }
            }
        }
    },
    close: function () {
        this.$avatarModal.modal('hide');
    },
    alert: function (msg) {
        var $alert = [
            '<div class="alert alert-danger avater-alert">',
            '<button type="button" class="close" data-dismiss="alert">&times;</button>',
            msg,
            '</div>'
        ].join('');

        this.$avatarUpload.after($alert);
    }
};



